import axios from 'axios';
import store from '@/store';

const service = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000
});

service.interceptors.request.use(
  config => {
    const token = store.state.token;
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  error => Promise.reject(error)
);

service.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response && error.response.status === 401) {
      store.commit('logout');
      window.location = '/login';
    }
    return Promise.reject(error);
  }
);

export default service;
